package com.shengyuan.manage_os.old.ying.erpm.tasks;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.shengyuan.manage_os.old.ying.boce.jsy.APIErpm;
import com.shengyuan.manage_os.old.ying.boce.task.GenericTask;
import com.shengyuan.manage_os.old.ying.boce.task.TaskParams;
import com.shengyuan.manage_os.old.ying.boce.task.TaskResult;

public class SubmitUpdateTask extends GenericTask
{
	public static String UPDATEFILE = "updatefile";
	private String Message = "";
	public String getMsg() {
		return Message;
	}
	private  void InputStreamtoFile(InputStream ins,File file) {
		  try {
		   OutputStream os = new FileOutputStream(file);
		   int bytesRead = 0;
		   byte[] buffer = new byte[8192];
		   while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
		    os.write(buffer, 0, bytesRead);
		   }
		   os.close();
		   ins.close();
		  } catch (Exception e) {
		   e.printStackTrace();
		  }
	}


	@Override
	protected TaskResult _doInBackground(TaskParams... params) {
		try {
			TaskParams param= params[0];
			String fileurl = param.getString(UPDATEFILE);

			InputStream inStream = null;
	    	String path = (new APIErpm()).getUpdateXml();
	    	try {
		    	URL url = new URL(path);   
		        HttpURLConnection conn = (HttpURLConnection) url.openConnection();   
		        conn.setRequestMethod("GET");   
		        conn.setReadTimeout(6*1000);
		        if (conn.getResponseCode() == 200) { 
		        	inStream = conn.getInputStream();
		        }else {
		        	Message = "无升级文件";
		        	return TaskResult.FAILED;
				}			
		        File file = new File(fileurl);
		        InputStreamtoFile( inStream, file);
			} catch (Exception e) {
				Message = e.getMessage();
				return TaskResult.CANCELLED;
			}
			return TaskResult.OK;
		} catch (Exception e) {
			Message = e.getMessage();
			return TaskResult.FAILED;
		}
	}
}